﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demos.DesignPatterns._13_代理模式
{
    /// <summary>
    /// 购物车实体
    /// </summary>
    public class ShopCartObject
    {
        public string UserId { get; set; } = string.Empty;

        public List<ShopCartItem> Items { get; set; } = new List<ShopCartItem>();

        public DateTime LastUpdated { get; set; } = DateTime.Now;
        public decimal CartTotal
        {
            get
            {
                decimal total = 0;
                foreach (var item in Items)
                {
                    total += item.TotalPrice;
                }
                return total;
            }
        }

        /// <summary>
        /// 添加商品到购物车
        /// </summary>
        /// <param name="newItem"></param>
        public void AddItem(ShopCartItem newItem)
        {
            var existingItem = Items.Find(i => i.ProductId == newItem.ProductId);
            if (existingItem != null)
            {
                existingItem.Quantity += newItem.Quantity;
            }
            else
            {
                Items.Add(newItem);
            }
            LastUpdated = DateTime.Now;
        }

        /// <summary>
        /// 从购物车中移除商品
        /// </summary>
        /// <param name="productId"></param>
        public void RemoveItem(string productId)
        {
            Items.RemoveAll(i => i.ProductId == productId);
            LastUpdated = DateTime.Now;
        }


    }
}
